package com.nexgo.payment.download;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.Gravity;

import com.google.gson.Gson;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpGet;
import com.koushikdutta.async.http.AsyncHttpResponse;
import com.koushikdutta.async.parser.StringParser;
import com.koushikdutta.async.util.Charsets;
import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.download.listener.OnCheckListener;
import com.nexgo.payment.entity.UpdateInfo;
import com.nexgo.payment.fragment.TextDialogFragment;
import com.nexgo.payment.util.AppUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.HttpURLConnection;

/**
 * 检查是否有新版本
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年12月05日
 */
public class UpdateHelper {
    private Logger mLog = LoggerFactory.getLogger(UpdateHelper.class.getSimpleName());
    private static final String MD_5 = "md_5";
    private static final String VERSION_NAME = "version_name";
    private static final String DOWNLOAD_URL = "download_url";
    private static final String IS_AUTO_INSTALL = "is_auto_install";

    //上下文
    private FragmentActivity mActivity;
    //检查新版本地址
    private String mCheckUrl;
    //有新版本是否自动下载
    private boolean mIsAutoInstall;
    //当前应用的版本号
    private int mVersionCode;
    //是否有新版本
    private boolean mIsNewVersion;
    //版本更新信息
    private UpdateInfo updateInfo;
    //检查结果回调
    private OnCheckListener mCheckListener;

    public UpdateHelper(FragmentActivity mActivity) {
        this.mActivity = mActivity;
    }

    /**
     * 检查地址
     *
     * @param checkUrl
     * @return
     */
    public UpdateHelper setCheckUrl(String checkUrl) {
        this.mCheckUrl = checkUrl;
        mLog.debug("mCheckUrl : {}", checkUrl);
        return this;
    }

    /**
     * 自动安装
     *
     * @param isAutoInstall
     * @return
     */
    public UpdateHelper setIsAutoInstall(boolean isAutoInstall) {
        this.mIsAutoInstall = isAutoInstall;
        mLog.debug("mIsAutoInstall : {}", isAutoInstall);
        return this;
    }

    /**
     * 检查结果回调
     *
     * @param checkListener
     * @return
     */
    public UpdateHelper setCheckListener(OnCheckListener checkListener) {
        this.mCheckListener = checkListener;
        return this;
    }

    /**
     * 开始检查
     */
    public void build(){
        if (TextUtils.isEmpty(mCheckUrl)) return;
        //开始检查
        if (mCheckListener != null) mCheckListener.onStart();
        AsyncHttpClient.getDefaultInstance().execute(new AsyncHttpGet(mCheckUrl), new StringParser(Charsets.UTF_8),
                new AsyncHttpClient.RequestCallbackBase<String>() {
                    @Override
                    public void onCompleted(Exception e, AsyncHttpResponse source, String result) {
                        if (e != null){
                            e.printStackTrace();
                            if (mCheckListener != null) mCheckListener.onError(e);
                            return;
                        }
                        mLog.debug("响应码 code : {}", source.code());
                        //先判断响应码是否正确
                        if (source.code() != HttpURLConnection.HTTP_OK || TextUtils.isEmpty(result)){
                            if (mCheckListener != null) mCheckListener.onError(null);
                        }
                        int index = result.trim().indexOf("{");
                        result = result.substring(index);
                        mLog.debug("result : {}", result);
                        try {
                            if (updateInfo != null) updateInfo = null;
                            //解析返回json串
                            updateInfo = new Gson().fromJson(result, UpdateInfo.class);
                            //获取当前版本号
                            mVersionCode = AppUtils.getAppVersionCode(App.sContext);
                            //判断应用版本号
                            mIsNewVersion = updateInfo.getVersionCode() > mVersionCode;
                            mLog.debug("当前版本号 : {}, 最新版本号 : {}", mVersionCode, updateInfo.getVersionCode());
                            if (mCheckListener != null) mCheckListener.onResult(mIsNewVersion);
                            if (mIsNewVersion){
                                //如果是强制更新，直接启动下载服务
                                if (updateInfo.isForceUpdate()){
                                    mIsAutoInstall = true;  //重置成自动安装
                                    startDownloadService();
                                    return;
                                }
                                showDialogUpdateInfo();
                            }
                        }catch (Exception e1){
                            e1.printStackTrace();
                            if (mCheckListener != null) mCheckListener.onError(e1);
                        }
                    }
                });
    }

    /**
     * 弹出层提示有新版本
     */
    private void showDialogUpdateInfo(){
        if (updateInfo == null) return;
        TextDialogFragment dialogFragment = new TextDialogFragment();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_SUCCESS);
        dialogFragment.setTitleText(App.sContext.getString(R.string.version_info_tips));
        dialogFragment.setContentText(updateInfo.toString(), Gravity.LEFT);
        dialogFragment.setNegativeText(App.sContext.getString(R.string.cancel));
        dialogFragment.setPositionText(App.sContext.getString(R.string.confirm));
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {}

            @Override
            public void onConfirm() {
                startDownloadService();
            }
        });
        dialogFragment.show(mActivity.getSupportFragmentManager(), null);
    }

    /**
     * 启动下载服务
     */
    private void startDownloadService(){
        if (updateInfo == null) return;
        Intent intent = new Intent(App.sContext, DownloadService.class);
        Bundle bundle = new Bundle();
        bundle.putString(MD_5, updateInfo.getMd5());
        bundle.putString(VERSION_NAME, updateInfo.getVersionName());
        bundle.putString(DOWNLOAD_URL, updateInfo.getUrl());
        bundle.putBoolean(IS_AUTO_INSTALL, mIsAutoInstall);
        intent.putExtras(bundle);
        mActivity.startService(intent);
    }
}
